import axios, { type AxiosRequestConfig, type AxiosResponse } from "axios";
// 创建 axios 实例
const request = axios.create({
  baseURL: "http://localhost:8123/chiyu-security-user/",
  withCredentials: true,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证 token
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data;
  },
  (error) => {
    if (error.response?.status === 40100) {
      // token 过期或未授权，跳转到登录页
      localStorage.removeItem("token");
      window.location.href = "/login";
    }
    return Promise.reject(error);
  },
);

// 重新定义 request 方法的类型，使其返回直接的数据类型而不是 AxiosResponse
const customRequest = {
  get: <T>(url: string, config?: AxiosRequestConfig) => {
    return request.get<T, T>(url, config);
  },
  post: <T>(url: string, data?: any, config?: AxiosRequestConfig) => {
    return request.post<T, T>(url, data, config);
  },
  put: <T>(url: string, data?: any, config?: AxiosRequestConfig) => {
    return request.put<T, T>(url, data, config);
  },
  delete: <T>(url: string, config?: AxiosRequestConfig) => {
    return request.delete<T, T>(url, config);
  },
};

export default customRequest;
